import gzip
import  Bio
import os,sys

from Bio.PDB.PDBParser import PDBParser




pdb_stock='/net/stockage/bioinfoDM/pdb/'
path_xml='xml_pdb.xml'# chemin de sortie a modifier  



list_pdb=sorted(os.listdir(pdb_stock))
list_invader = ["4dnb.gz","4bna.gz","3ltu.gz","3k1v.gz","3hg8.gz","3dix.gz","363d.gz","2v6w.gz","2pn3.gz","2b8s.gz","290d.gz","266d.gz","236d.gz","1zx7.gz","1z43.gz","1y0q.gz","1qpy.gz","1nlc.gz","1mme.gz","1d82.gz","1d61.gz","1d26.gz","1ana.gz","159d.gz"]
list_invader.sort
list_aa = { "ALA" : "A", "ARG" : "R", "ASN" : "N","ASP" : "D", "CYS" : "C", "GLU" : "E","GLN" : "Q", "GLY" : "G", "HIS" : "H","ILE" : "I", "LEU" : "L", "LYS" : "K", "MET" : "M", "PHE" : "F", "PRO" : "P","PYL" : "O", "SEC" : "U", "SER" : "S","THR" : "T",  "TRP" : "W", "TYR" : "Y","VAL" : "V"  }
for i in list_invader:
	list_pdb.remove(i)


output = open(path_xml ,"w")
output.write("<?xml version='1.0' encoding='UTF-8'?>\n"+"<database>\n")
parser = PDBParser(PERMISSIVE=1) #(PERMISSIVE=1) gestion d'erreurs lies aux pdb


for pdb in list_pdb:
#~ for k in range (10):
	#~ pdb='102l.gz'
	invader2= None

	#print pdb
	
	seq = ''
	nb_chain=0
	percent_cys=0
	nb_cys=0
	
	nbre_aa = 0
	decompress = gzip.open(pdb_stock+pdb, 'rb')  #decompression
	pdb_id =   pdb.split('.')[0]
	structure = parser.get_structure(pdb_id ,decompress)
	header = parser.get_header()
	model = structure[0]	
	name = header['compound']['1']['molecule']
	for chain in model :
		nb_chain=nb_chain+1
		for residue in chain :
			if (residue.resname in [" DA", " DT", " DG", " DC","  A", "  T", "  G", "  C", "  U","UNK"]):
				invader2 = False
				
			#~ print residue
			else :
				invader2=True
				for i in list_aa.keys():
					if residue.resname == i :
						#~ print "bah ", list_aa[i]
						seq= seq +list_aa[i]
						nbre_aa = nbre_aa + 1
						if i =="C":
							nb_cys=nb_cys+1
	percent_cys= (100*nb_cys)/nbre_aa
	if (invader2 == True ) :
		output.write("<molecule>\n")
		output.write("<header>" + name +" "+pdb_id+"</header>\n")          
		output.write("<size>" + str(nbre_aa)+"</size>\n")
		output.write("<nb_chain>" + str(nb_chain)+"</nb_chain>\n")
		output.write("<sequence>" + seq+"</sequence>\n")
		output.write("<percent_cysteine>" + str(percent_cys)+"</percent_cysteine>\n")
		output.write("</molecule>")
output.write("</database>")

